package com.topscomm.mis.cbb.file.compare.word.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.Config;
import com.topscomm.mis.cbb.file.compare.word.constants.WordConstants;
import com.topscomm.pub.util.ConvertUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 文件处理进度缓存类
 * 
 * @description:
 * @author: donghang
 * @date: 2021年5月13日下午5:06:43
 * @modify:
 */
public class FileProcessProgressCache {
	/**
	 * 缓存
	 */
	private static Cache<String, Map<String, Object>> cache;
	/**
	 * 缓存过期时间(秒)，7天的时间
	 */
//	private static int CACHELIVETIME = Config.getInstance().getIntValue("fileprocess.cache.cachelivetime",
//			60 * 60 * 24 * 7);
	private static int CACHELIVETIME = 60 * 60 * 24 * 7;
	/**
	 * 静态块
	 */
	static {
		cache = CacheBuilder.newBuilder().maximumSize(10000).expireAfterWrite(CACHELIVETIME, TimeUnit.SECONDS).build();
	}

	/**
	 * 得到文件处理进度
	 * 
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2021年5月13日下午5:18:32
	 * @modify:
	 */
	public static int getProgress(String key) {
		try {

			Map<String, Object> valueMap = cache.getIfPresent(key);
			if (valueMap == null) {
				return WordConstants.FileProcessProgressType.Error;
			}
			int count = ConvertUtil.convertToInt(valueMap.get("count"));
			// 当前进度
			int current = ConvertUtil.convertToInt(valueMap.get("current"));
			// 代表处理完成
			if (current == WordConstants.FileProcessProgressType.Finish) {
				return WordConstants.FileProcessProgressType.Finish;
			} else if (current == WordConstants.FileProcessProgressType.Error) {
				return WordConstants.FileProcessProgressType.Error;
			} else if (count != 0) {
				return (int) (((float) current) / count * 100);
			} else {
				return 0;
			}
		} catch (Exception e) {
			throw new ServiceException("缓存异常");
		}
	}

	/**
	 * 得到值
	 * 
	 * @description:
	 * @param key
	 * @return
	 * @author: donghang
	 * @date: 2021年5月15日上午9:41:07
	 * @modify:
	 */
	public static Map<String, Object> getValue(String key) {
		try {
			return cache.getIfPresent(key);
		} catch (Exception e) {
			throw new ServiceException("缓存异常");
		}
	}

	/**
	 * 添加值
	 * 
	 * @description:
	 * @param key
	 * @param count
	 * @author: donghang
	 * @date: 2021年5月13日下午5:28:48
	 * @modify:
	 */
	public static void putValue(String key, int count, int page, String message) {
		Map<String, Object> valueMap = new HashMap<>();
		valueMap.put("count", count);
		valueMap.put("current", page);
		valueMap.put("message", message);
		cache.put(key, valueMap);
	}
}
